package com.xyd.Util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class SqlSessionFactoryUtil {
    private static SqlSessionFactory factory = null;
    private static String LOCA = "Mybatis_core.xml";
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    private static SqlSession sqlSession;

    static {
        try {
            init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void init() throws IOException {
        Reader reader = Resources.getResourceAsReader(LOCA);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        factory = builder.build(reader);
        reader.close();
    }

    public static SqlSession open() {
        if (threadLocal.get() == null) {
            sqlSession = factory.openSession();
            threadLocal.set(sqlSession);
        }
        return threadLocal.get();
    }

    public static void close() {
        if (threadLocal.get() == null) {
            sqlSession = factory.openSession();
            threadLocal.set(sqlSession);
        }
        sqlSession = threadLocal.get();
        System.out.println("[sqlsession]:"+sqlSession.hashCode()+"\t关闭");
        sqlSession.close();
        threadLocal.remove();
    }

    public static void rollback() {
        if (threadLocal.get() == null) {
            sqlSession = factory.openSession();
            threadLocal.set(sqlSession);
        }
        sqlSession = threadLocal.get();
        sqlSession.rollback();
    }

    public static void commit() {
        if (threadLocal.get() == null) {
            sqlSession = factory.openSession();
            threadLocal.set(sqlSession);
        }
        System.out.println("[sqlsession]:"+sqlSession.hashCode()+"\t提交");
        sqlSession = threadLocal.get();
        sqlSession.commit();
    }
}
